package fu.k4c.vTeam.Login;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import fu.k4c.vTeam.R;
import fu.k4c.vTeam.Main.MainActivity;
import fu.k4c.vTeam.Object.Account;
import fu.k4c.vTeam.Object.Regis;

public class RegisActivity extends Activity {
	String fullname;

	ProgressDialog proDialog;
	String[] checkFullName = { "Admin", "admin", "Hồ Chí Minh", "Smod", "smod",
			"mod", "Seniormod", "Mod", "Bố admin", "Bác Hồ" };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.regis_activity);
		overridePendingTransition(android.R.anim.fade_in,
				android.R.anim.fade_out);
		final EditText et_email = (EditText) findViewById(R.id.et_regis_email);
		final EditText et_pass = (EditText) findViewById(R.id.et_regis_pass);
		final EditText et_repass = (EditText) findViewById(R.id.et_regis_repass);
		final EditText et_name = (EditText) findViewById(R.id.et_regis_name);
		Button btn_back = (Button) findViewById(R.id.btn_regis_back);
		btn_back.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		Button btn_qdsddv = (Button) findViewById(R.id.btn_regis_qdsddv);
		btn_qdsddv.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(RegisActivity.this,
						RegisLawActivity.class);
				startActivity(i);
			}
		});
		Button btn_submit = (Button) findViewById(R.id.btn_regis_submit);
		btn_submit.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				new AsyncTask<Void, Void, Void>() {
					Account acc;
					Regis user;

					@Override
					protected Void doInBackground(Void... params) {
						// TODO Auto-generated method stub
						runOnUiThread(new Runnable() {
							public void run() {
									if (isEmailValid(et_email.getText()
											.toString().trim()) == false) {
										Toast.makeText(getApplicationContext(),
												"Nhập lại email",
												Toast.LENGTH_LONG).show();
									} else if (et_pass
											.getText()
											.toString()
											.trim()
											.equals(et_repass.getText()
													.toString().trim()) == false) {
										Toast.makeText(getApplicationContext(),
												"Nhập lại mật khẩu",
												Toast.LENGTH_LONG).show();
									} else {
										if (et_pass.getText().toString().trim()
												.length() < 6) {
											Toast.makeText(
													getApplicationContext(),
													"Nhập lại mật khẩu",
													Toast.LENGTH_LONG).show();
										} else {

											if (et_name.getText().toString()
													.trim().equals("") == false
													&& et_name.getText()
															.toString().trim() != null) {
												fullname = et_name.getText()
														.toString().trim();
											} else {
												String[] tmp;
												tmp = et_email.getText()
														.toString().trim()
														.split("@");
												fullname = tmp[0];

											}
											Boolean isCheck = false;
											for (int i = 0; i < checkFullName.length; i++) {
												if (fullname.toLowerCase()
														.indexOf(checkFullName[i]) >= 0) {
													isCheck = true;
												}
											}
											if (isCheck == true) {
												Toast.makeText(
														getApplicationContext(),
														"Tên hiển thị sai quy định",
														Toast.LENGTH_LONG)
														.show();
											} else {
												try {
													SchemeRegistry registry = new SchemeRegistry();
													registry.register(new Scheme(
															"http",
															PlainSocketFactory
																	.getSocketFactory(),
															80));
													HttpParams httpParams = new BasicHttpParams();
													ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
															httpParams,
															registry);
													HttpClient client = new DefaultHttpClient(
															connMgr, httpParams);
													HttpPost post = new HttpPost(
															getString(R.string.connectionString)
																	+ "vLocationService/register");
													post.setHeader("Accept",
															"application/json");
													post.setHeader(
															"Content-type",
															"application/json");
													HashMap<String, Object> postParameters = new HashMap<String, Object>();

													user = new Regis(
															et_email.getText()
																	.toString()
																	.trim(),
															encryptPassword(et_pass
																	.getText()
																	.toString()
																	.trim()),
															fullname);

													postParameters.put(
															"UserName",
															user.getUsername());
													postParameters.put(
															"Password",
															user.getPassword());
													postParameters.put(
															"FullName",
															user.getFullName());
													Gson gson = new Gson();
													String jsonParameters = gson
															.toJson(postParameters);
													// Toast.makeText(getApplicationContext(),"up"
													// + jsonParameters,
													// Toast.LENGTH_LONG).show();
													// tv_valid.setText(postParameters.toString());
													post.setEntity(new StringEntity(
															jsonParameters,
															"UTF-8"));
													HttpResponse response = client
															.execute(post);

													HttpEntity entity = response
															.getEntity();
													String jsonresult = EntityUtils
															.toString(entity);

													acc = gson.fromJson(
															jsonresult,
															Account.class);
													// Toast.makeText(getApplicationContext(),jsonresult,
													// Toast.LENGTH_LONG).show();

												} catch (Exception e) {
													// TODO: handle exception
													Toast.makeText(
															getApplicationContext(),
															"Bạn vui lòng kiểm tra lại kết nối Internet ",
															Toast.LENGTH_LONG)
															.show();
												}
											}
										}
									}
								
							}
						});
						return null;
					}

					protected void onPostExecute(Void result) {
						proDialog.dismiss();
						try {
							if (acc.getStatus().equals("False")) {
								Toast.makeText(getApplicationContext(),
										"Email đã tồn tại", Toast.LENGTH_LONG)
										.show();
							} else {
								Toast.makeText(getApplicationContext(),
										"Đăng kí thành công!",
										Toast.LENGTH_LONG).show();
								Intent i = new Intent(RegisActivity.this,
										MainActivity.class);
								i.putExtra("status", acc.getStatus());
								i.putExtra("email", user.getUsername());
								i.putExtra("fullName", fullname);
								startActivity(i);
							}
						} catch (Exception e) {
							// TODO: handle exception
						}
					};

					protected void onPreExecute() {
						proDialog = new ProgressDialog(RegisActivity.this);
						proDialog.setMessage("Đang kết nối đến máy chủ...");
						proDialog.setCancelable(false);
						proDialog.show();
					};

					protected void onProgressUpdate(Void... values) {
					}

				}.execute();

			}
		});
	}

	public static boolean isEmailValid(String email) {
		boolean isValid = false;

		String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
		CharSequence inputStr = email;

		Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		if (matcher.matches()) {
			isValid = true;
		}
		return isValid;
	}

	private static String encryptPassword(String password) {
		String sha1 = "";
		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(password.getBytes("UTF-8"));
			sha1 = byteToHex(crypt.digest());
			sha1 = sha1.toUpperCase();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return sha1;
	}

	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		return formatter.toString();
	}

	public boolean isConnectedToServer(String url, int timeout) {
		try {
			URL myUrl = new URL(url);
			URLConnection connection = myUrl.openConnection();
			connection.setConnectTimeout(timeout);
			connection.connect();
			return true;
		} catch (Exception e) {
			// Handle your exceptions
			return false;
		}
	}
}
